package com.scsj.supermarket.view.activity.mainmodel;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;

import com.orhanobut.logger.Logger;
import com.scsj.supermarket.R;
import com.scsj.supermarket.adapter.MainFragmentAdapter;
import com.scsj.supermarket.event.FirstEvent;
import com.scsj.supermarket.utils.BaiduMapHelper;
import com.scsj.supermarket.utils.ExampleUtil;
import com.scsj.supermarket.utils.LocalBroadcastManager;
import com.scsj.supermarket.utils.RxBus;
import com.scsj.supermarket.view.activity.baseactivitymodel.BaseActivity;
import com.scsj.supermarket.view.fragment.basemodel.BaseFragment;
import com.scsj.supermarket.view.fragment.fivepagemodel.ClassifyFragment;
import com.scsj.supermarket.view.fragment.fivepagemodel.MapFragment;
import com.scsj.supermarket.view.fragment.fivepagemodel.MineFragment;
import com.scsj.supermarket.view.fragment.fivepagemodel.MyHomeFragment;
import com.scsj.supermarket.view.fragment.fivepagemodel.ShoppingFragment;
import com.scsj.supermarket.view.fragment.marketmodel.MarketFragment;

import java.util.ArrayList;

import cn.jpush.android.api.JPushInterface;
import devlight.io.library.ntb.NavigationTabBar;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


/**
 * 主页面
 * 主程序
 */
public class MainActivity extends BaseActivity {

    public static boolean isForeground = false;
    private ViewPager viewPager;

    @Override
    protected void createView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        intiNavigationBar();
        initView();
        initData();
        initListener();
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {
        //获取定位信息
        getLocationInfo();


    }

    private void getLocationInfo() {
        BaiduMapHelper
                .getInstance()
                .init(null)
                .params(this)
                .showLocation();

        RxBus.getDefault().toObservable(FirstEvent.class)
                //在io线程进行订阅，可以执行一些耗时操作
                .subscribeOn(Schedulers.io())
                //在主线程进行观察，可做UI更新操作
                .observeOn(AndroidSchedulers.mainThread())
                //观察的对象
                .subscribe(new Action1<FirstEvent>() {
                    @Override
                    public void call(FirstEvent firstEvent) {
                        if (firstEvent.getCode().equals("location")) {

                        }
                    }
                });
    }

    private void intiNavigationBar() {
        viewPager = findViewById(R.id.vp);
        viewPager.setOffscreenPageLimit(5);

        ArrayList<BaseFragment> fragmentList = new ArrayList<>();

        MyHomeFragment myHomeFragment = new MyHomeFragment();
        MapFragment mapFragment = new MapFragment();
        ClassifyFragment secondFragment = new ClassifyFragment();
        ShoppingFragment forthFragment = new ShoppingFragment();
        MineFragment fiveFragment = new MineFragment();
        MarketFragment marketFragment = new MarketFragment();

        fragmentList.add(myHomeFragment);
        fragmentList.add(secondFragment);
        fragmentList.add(mapFragment);
        fragmentList.add(forthFragment);
        fragmentList.add(fiveFragment);

        MainFragmentAdapter mAdpter = new MainFragmentAdapter(getSupportFragmentManager(), fragmentList);
        viewPager.setAdapter(mAdpter);

        final NavigationTabBar navigationTabBar = findViewById(R.id.ntb);
        final ArrayList<NavigationTabBar.Model> models = new ArrayList<>();

        models.add(
                new NavigationTabBar.Model.Builder(
                        getResources().getDrawable(R.mipmap.home_unselected),
                        Color.parseColor("#FF314A"))
                        .title("首页")
                        .selectedIcon(getResources().getDrawable(R.mipmap.home_selected))
                        .build()
        );
        models.add(
                new NavigationTabBar.Model.Builder(
                        getResources().getDrawable(R.mipmap.sort_unselected),
                        Color.parseColor("#FF314A"))
                        .title("分类")
                        .selectedIcon(getResources().getDrawable(R.mipmap.sort_selected))
                        .build()

        );
        models.add(
                new NavigationTabBar.Model.Builder(
                        getResources().getDrawable(R.mipmap.map_unselected),
                        Color.parseColor("#FF314A"))
                        .title("商圈")
                        .selectedIcon(getResources().getDrawable(R.mipmap.map_selected))
                        .build()
        );
        models.add(
                new NavigationTabBar.Model.Builder(
                        getResources().getDrawable(R.mipmap.shopcar_unselected),
                        Color.parseColor("#FF314A"))
                        .title("购物车")
                        .selectedIcon(getResources().getDrawable(R.mipmap.shopcar_selected))
                        .build()
        );
        models.add(
                new NavigationTabBar.Model.Builder(
                        getResources().getDrawable(R.mipmap.mine_unselected),
                        Color.parseColor("#FF314A"))
                        .title("我的")
                        .selectedIcon(getResources().getDrawable(R.mipmap.mine_selected))
                        .build()
        );

        navigationTabBar.setModels(models);
        navigationTabBar.setViewPager(viewPager, 0);
        navigationTabBar.setBehaviorEnabled(false);
        navigationTabBar.setTitleMode(NavigationTabBar.TitleMode.ALL);
        navigationTabBar.setIsTitled(true);
        navigationTabBar.setIsTinted(false);
        navigationTabBar.setIsSwiped(false);
        navigationTabBar.setBgColor(Color.WHITE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            navigationTabBar.setNestedScrollingEnabled(false);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            navigationTabBar.setNestedScrollingEnabled(false);
        }
    }

    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.scsj.supermarket.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                    //  setCostomMsg(showMsg.toString());
                }
            } catch (Exception e) {
            }
        }
    }

    // 初始化 JPush。如果已经初始化，但没有登录成功，则执行重新登录。
    private void init() {
        JPushInterface.init(getApplicationContext());
    }

    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
    }

    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
        super.onDestroy();
    }

    /**
     * 跳转到指定的viewpager页面
     */
    public void skipToVP(int i) {
        if (i >= 0 && i < 5)
            viewPager.setCurrentItem(i);
    }
}